package haida.pym_system.config.shiro;
import haida.pym_system.site.mapper.UserMapper;
import haida.pym_system.site.pojo.User;
import haida.pym_system.site.service.IUserService;
import haida.pym_system.site.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * UserRealm
 *
 * @Description:
 * @Author: HongJie
 * @CreateTime: 2020-04-21
 */
public class UserRealm extends AuthorizingRealm {
	@Autowired
	UserServiceImpl userService;


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("执行了=》授权doGetAuthorizationInfo");
		//SimpleAuthorizationInfo
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// info.addStringPermission("user:add");

		Subject subject = SecurityUtils.getSubject();
		User currentUser = (User) subject.getPrincipal();  //拿到User对象

		info.addStringPermission(currentUser.getPrivilege());

		return info;
		// return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("执行了=》认证doGetAuthenticationInfo");
		//用户名，密码  数据中取
		// String name = "root";
		// String password = "123";

		UsernamePasswordToken userToken = (UsernamePasswordToken) token;
		// 连接真实的数据库
		User user = userService.findUserName(userToken.getUsername());
		// if (!userToken.getUsername().equals(name)){
		// 	return null;
		// }
		if (user == null) return null; //抛出异常 UnknownAccountException

		//可以加密：MD5：e1eadc3949ba59abbe56e057f2f883eMD5孟值加密：e1eadc3949ba59abbe56ee57f2ef883eusername
		//密码认证，shiro，加密了
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		System.out.println(user.getUserID()+"++++++++++++++");
		session.setAttribute("loginUser", user);

		return new SimpleAuthenticationInfo(user, user.getPassword(), "");
		// return null;
	}

}
